﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PowerCreator.LMS.Web.Course;
using PowerCreator.LMS.Common.Utils;
using PowerCreator.LMS.Course.Entity;

public partial class Theme_3_ProjectOpenCourseware : System.Web.UI.Page
{
    //更新学习资源，如果没有的参数，则使用0替换,1添加资源访问记录
    protected string _isUpdateCourse = "0";

    string _openhistoryurl = WebUtils.WebRoot + "/web/Project/OpenHistory.aspx?ProjectID={0}&ProjectClassID={1}&ProjectClassUserID={2}&ProjectResourceID={3}&CourseResourceID={4}&ResourceID={5}&ProjectResourceResourceStartTime={6}";

    protected string _url = "";  //更新课件访问信息URL
    protected string _fileUrl = "";
    protected string _UserID = "";//用户ID

    protected string _vPowerCreator = "0";   //是否调PowerCreator课件界面,1调用，其它为不调用
    protected string _ResourceID = "0";

    protected string _ShowCommentP = "0";        //是否弹出提示信息

    PowerCreator.LMS.Web.Course.Course opCourse = new PowerCreator.LMS.Web.Course.Course();                     //课程管理
    PowerCreator.LMS.Web.Comment.Comment opComment = new PowerCreator.LMS.Web.Comment.Comment();
        
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitPage();
            string projectid = Request.QueryString["ProjectID"].ToString();
            ViewState["ProjectID"] = projectid;
            string projectclassid = Request.QueryString["ProjectClassID"].ToString();
            ViewState["ProjectClassID"] = projectclassid;
            string projectresourceid = Request.QueryString["ProjectResourceID"].ToString();
            ViewState["ProjectResourceID"] = projectresourceid;
            string courseresourceid = Request.QueryString["CourseResourceID"].ToString();
            ViewState["CourseResourceID"] = courseresourceid;
            string resourceid = Request.QueryString["ResourceID"].ToString();
            ViewState["ResourceID"] = resourceid;
            
            ViewState["UserID"] = "0";

            BinderPage();
            pl_coursewarecomment.Visible = true;
        }
    }

    private void BinderPage()
    {
        _ResourceID = ViewState["ResourceID"].ToString();
        VOTResource vo = opCourse.LoadResource(int.Parse(ViewState["ResourceID"].ToString()));
        
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] != null)
        {
            PowerCreator.LMS.Web.User.LoginEntity login = (PowerCreator.LMS.Web.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
            ViewState["UserID"] = login.UserID.ToString();
        }
        _UserID = ViewState["UserID"].ToString();

        _fileUrl = WebUtils.WebRoot + vo.ResourceUrl + vo.ResourceEntry;

        if (vo.ResourceClass == Convert.ToInt16(SysResourceType.PowerCreator))
        {
            _vPowerCreator = "1";
            pl_PowerCreaotr.Visible = true;
            pl_coursewarecomment.Visible = true;
            _ShowCommentP = "1";
            pl_Video.Visible = false;
            pl_Download.Visible = false;
            
            if (!vo.ResourceMmsUpdateState)
            {
                PowerCreator.LMS.Web.Course.Resource opResource = new Resource();
                VOTCourseResource voCourseResource = opCourse.LoadCourseResource(int.Parse(ViewState["CourseResourceID"].ToString()));
                if (voCourseResource.CourseresID > 0)
                {
                    VOTOCourse voCourse = opCourse.LoadVOTCourse(voCourseResource.FKCourseresCourseID);
                    if (voCourse.Course_Id > 0)
                    {
                        opResource.UpdataResourceByEditMMS(vo);
                    }
                }
            }
        }
        else if (vo.ResourceClass == Convert.ToInt16(SysResourceType.Video))
        {
            _vPowerCreator = "0";
            pl_PowerCreaotr.Visible = false;
            pl_Video.Visible = true;
            pl_Download.Visible = false;
            pl_coursewarecomment.Visible = false;
        }
        else if (vo.ResourceClass == Convert.ToInt16(SysResourceType.Download))
        {
            _vPowerCreator = "0";
            //绑定界面数据
            lbl_CreatedTime.Text = vo.ResourceCreatedTime.ToString("yyyy/MM/dd");
            lbl_DownloadCount.Text = vo.ResourceClickNum.ToString();
            lbl_LastTime.Text = vo.ResourceLastVisitTime.ToString("yyyy/MM/dd");
            lbl_ResourceName.Text = vo.ResourceName;
            li_Description.Text = vo.ResourceDescription;
            hyplnk_FileUrl.NavigateUrl = _fileUrl;
            hyplnk_ImgFileurl.NavigateUrl = _fileUrl;
            //hyplnk_ImgFileurl.Target = "_";
            pl_PowerCreaotr.Visible = false;
            pl_Video.Visible = false;
            pl_coursewarecomment.Visible = false;
            pl_Download.Visible = true;
        }
        else if (vo.ResourceClass == Convert.ToInt16(SysResourceType.NoPowerCreator))
        {
            _vPowerCreator = "1";
            pl_PowerCreaotr.Visible = true;
            pl_coursewarecomment.Visible = false;
            pl_Video.Visible = false;
            pl_Download.Visible = false;
        }
        else if (vo.ResourceClass == Convert.ToInt16(SysResourceType.WebCourseware))
        {
            _vPowerCreator = "1";
            pl_PowerCreaotr.Visible = true;
            pl_coursewarecomment.Visible = true;
            pl_Video.Visible = false;
            pl_Download.Visible = false;
        }

        SetOpenHistoryUrl();
        //显示评论
        BinderComment();
    }
    private void SetOpenHistoryUrl()
    {
        _url = string.Format(_openhistoryurl, ViewState["ProjectID"], ViewState["ProjectClassID"].ToString(), ViewState["UserID"].ToString(), ViewState["ProjectResourceID"], ViewState["CourseResourceID"], ViewState["ResourceID"], DateTime.Now.ToString());
        _isUpdateCourse = "1";
    }
    protected void InitPage()
    {
        //base.InitPage();
    }

    protected void imgbtn_FileDown_Click(object sender, ImageClickEventArgs e)
    {
        VOTResource vo = opCourse.LoadResource(int.Parse(ViewState["ResourceID"].ToString()));

        _fileUrl = WebUtils.WebRoot + vo.ResourceUrl + vo.ResourceEntry;
        string path = Server.MapPath(_fileUrl);

        if (System.IO.File.Exists(path))
        {
            try
            {
                //打开要下载的文件
                System.IO.FileStream r = new System.IO.FileStream(path, System.IO.FileMode.Open);
                //设置基本信息

                Response.Buffer = false;
                Response.AddHeader("Connection", "Keep-Alive");
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(path));
                Response.AddHeader("Content-Length", r.Length.ToString());

                while (true)
                {
                    //开辟缓冲区空间
                    byte[] buffer = new byte[1024];
                    //读取文件的数据
                    int leng = r.Read(buffer, 0, 1024);
                    if (leng == 0)//到文件尾，结束
                        break;
                    if (leng == 1024)//读出的文件数据长度等于缓冲区长度，直接将缓冲区数据写入
                        Response.BinaryWrite(buffer);
                    else
                    {
                        //读出文件数据比缓冲区小，重新定义缓冲区大小，只用于读取文件的最后一个数据块
                        byte[] b = new byte[leng];
                        for (int i = 0; i < leng; i++)
                            b[i] = buffer[i];
                        Response.BinaryWrite(b);
                    }
                }
                r.Close();//关闭下载文件
                Response.End();//结束文件下载
            }
            catch (Exception ex)
            {
                //BaseWriteLog(ex.Message);
                lab_err.Text = "文件下载出现意外，请联系管理员!异常描述：" + ex.Message;
            }

            vo.ResourceClickNum += 1;
            vo.ResourceLastVisitTime = DateTime.Now;
            if (!opCourse.UpdateResource(vo))
            {
                lab_err.Text = "注意：程序出现意外，请联系管理员！";
            }
        }
        else
        {

        }
    }
    private void BinderComment()
    { 
        //绑定评论
        string search =string.Format( " ResourceID= {0} and IsShow = 1 ",ViewState["ResourceID"]);
        int pageSize = opComment.QueryCommentCount(search);
        lblCommentCount.Text = pageSize.ToString();
        DataTable dt = opComment.QueryComment(search, pageSize, 1);
        dt.Columns.Add("NewPlayTime");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["NewPlayTime"] = PowerCreator.LMS.Common.Utils.TimeUtils.GetTimeQian(dt.Rows[i]["PlayTime"].ToString());
        }
        rptCommentList.DataSource = dt;
        rptCommentList.DataBind();
    }
    protected void rptCommentList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {

    }
}
